<template>
  <div class="bom-container">
    <div>
      <el-button :icon="Plus" plain type="primary" @click="query">
        查询
      </el-button>
      <el-button
        :icon="SuccessFilled"
        plain
        type="primary"
        @click="baocunqidong = true"
      >
        保存
      </el-button>
      <el-button plain type="primary" @click="addNoBom()">
        <vab-icon icon="sort-desc" />
        增行（未有bom）
      </el-button>
    </div>
    <el-divider />
    <el-row>
      <el-col :span="6">
        <el-table
          :border="true"
          :cell-style="{ padding: '0px' }"
          :data="state.bomData"
          default-expand-all
          :highlight-current="true"
          row-key="pkBomB"
          :row-style="{ height: '20px' }"
          size="small"
          style="width: 100%; margin-bottom: 20px; font-size: 10px"
          :tree-props="{ children: 'mesBomBs' }"
          @row-click="bomTreeRowClick"
        >
          <el-table-column
            :fixed="true"
            label="存货编码"
            min-width="100"
            prop="invcode"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :fixed="true"
            label="存货名称"
            min-width="100"
            prop="invname"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="规格型号" min-width="150">
            <template #default="scope">
              <el-row>
                <span>{{ scope.row.invspec }}</span>
              </el-row>
              <el-row>
                <span style="font-size: 12px">{{ scope.row.invtype }}</span>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="18">
        <el-form :disabled="true" label-width="120px" :model="state.form">
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="母件编码">
                <el-input v-model="state.xzBom.invcode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="母件名称">
                <el-input v-model="state.xzBom.invname" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="母件规格">
                <el-input v-model="state.xzBom.invspec" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="母件型号">
                <el-input v-model="state.xzBom.invtype" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注">
                <el-input v-model="state.xzBom.remark" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="" />
        </el-form>
        <el-row justify="center">
          <el-col :span="24">
            <el-table
              :data="state.xzBom.mesBomBs"
              default-expand-all
              :row-class-name="tableRowClassName"
              row-key="pkBomB"
              :row-style="{ height: '20px' }"
              size="small"
              style="width: 100%; font-size: 10p"
              :tree-props="{ children: 'tds' }"
            >
              <el-table-column label="行" prop="hh" width="50" />
              <el-table-column
                align="center"
                label="工序"
                prop="opName"
                width="120"
              >
                <template #default="scope">
                  <el-select
                    v-show="!scope.row.isTd"
                    v-model="scope.row.pkGx"
                    class="m-2"
                    filterable
                    placeholder="选择"
                    size="small"
                  >
                    <el-option
                      v-for="gx in state.gxs"
                      :key="gx.pkOperation"
                      :label="gx.opName"
                      :value="gx.pkOperation"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="编码名称" width="200">
                <template #default="scope">
                  <el-row>
                    <span>{{ scope.row.invcode }}</span>
                  </el-row>
                  <el-row>
                    <span style="font-size: 12px">{{ scope.row.invname }}</span>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column label="规格型号" width="200">
                <template #default="scope">
                  <el-row>
                    <span>{{ scope.row.invspec }}</span>
                  </el-row>
                  <el-row>
                    <span style="font-size: 12px">{{ scope.row.invtype }}</span>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="计量"
                prop="measname"
                width="80"
              />
              <el-table-column
                align="center"
                label="子数量"
                prop="childSl"
                width="70"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.childSl" size="small" />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="母数量"
                prop="parentSl"
                width="70"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.parentSl" size="small" />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="领用"
                prop="parentSl"
                width="70"
              >
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.isLingyong"
                    active-text="是"
                    :active-value="true"
                    inactive-text="否"
                    :inactive-value="false"
                    inline-prompt
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="是否到冲"
                prop="parentSl"
                width="100"
              >
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.dcPicking"
                    active-text="是"
                    :active-value="true"
                    inactive-text="否"
                    :inactive-value="false"
                    inline-prompt
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="替代" prop="td" width="50">
                <template #default="scope">
                  <span v-show="!scope.row.td && !scope.row.isTd">无</span>
                  <span v-show="scope.row.td" class="ml-2" type="danger">
                    有
                  </span>
                  <span v-show="scope.row.isTd" class="ml-2" type="warning">
                    是
                  </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="300">
                <template #default="scope">
                  <el-button
                    v-show="!scope.row.isTd"
                    size="small"
                    @click="jiaTidai(scope.$index, scope.row)"
                  >
                    加替代
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                  >
                    删行
                  </el-button>
                  <el-button
                    v-show="!scope.row.isTd"
                    size="small"
                    type="primary"
                    @click="zengXiayihang(scope.$index, scope.row)"
                  >
                    增下行
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <xuanzeInv ref="xzi" @selected-callback="selectedCallback" />
    <xzTdinv ref="xztd" @selected-callback="selectedCallback" />
    <XuanzeZengjia ref="xzZengjiaInv" @selected-callback="selectedCallback" />
    <el-dialog v-model="baocunqidong" title="维护版本并保存">
      <span>确定保存</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="baocunqidong = false">取消</el-button>
          <el-button type="primary" @click="quedingBaocun">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { Plus, SuccessFilled } from '@element-plus/icons-vue'
  import { getBomApi, getOperForBomApi, updateApi } from '@/api/mes/bom_api'
  import xuanzeInv from '@/plugins/InventorySelector/invSelect.vue'
  import xzTdinv from '@/plugins/InventorySelector/invSelect.vue'
  import XuanzeZengjia from '@/plugins/InventorySelector/invSelect.vue'
  import { localStorageConfig } from '@/config/localstorage.config'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
  const $baseMessage = inject('$baseMessage')

  const xzi = ref()
  const xztd = ref()
  const xzZengjiaInv = ref()

  const state = reactive({
    bomData: [],
    xzBom: {},
    gxs: [],
    currentRowData: {},
    currentIndex: 0,
    currentPk: '',
    zenghang: {
      hh: 0,
      index: 0,
    },
    xzInv: {
      pkInv: '',
      invcode: '',
    },
  })

  const baocunqidong = ref(false)

  const addNoBom = () => {
    if (state.xzBom.mesBomBs != null && state.xzBom.mesBomBs.length <= 0) {
      state.zenghang.hh = 1
      state.zenghang.index = 1
      xzi.value.handleOpen({ isComsume: 1 }, 1)
    } else {
      state.xzBom.mesBomBs = []
      state.xzBom.source = -1
      state.xzBom.version = 1
      state.xzBom.versionDesc = '版本1.0'
      state.xzBom.parentPkInv = state.xzBom.pkInv
      xzi.value.handleOpen({ isComsume: 1 }, 1)
    }
  }

  const zengXiayihang = (index, row) => {
    state.xzBom.mesBomBs.forEach((item, i) => {
      if (row.pkBomB === item.pkBomB) {
        let diff = 2
        if (i < state.xzBom.mesBomBs.length - 1) {
          diff = state.xzBom.mesBomBs[i + 1].hh - state.xzBom.mesBomBs[i].hh
        }
        if (diff > 1) {
          state.zenghang.hh = state.xzBom.mesBomBs[i].hh + 1
          state.zenghang.index = index
          xzZengjiaInv.value.handleOpen({ isComsume: 1 }, 1)
        }
      }
    })
  }

  const handleDelete = (index, row) => {
    state.xzBom.mesBomBs.forEach((item, index) => {
      if (item.pkBomB === row.pkBomB) {
        if (!row.isTd) {
          state.xzBom.mesBomBs.splice(index, 1)
        } else {
          item.tds.forEach((item2, index2) => {
            if (item2.hh === row.hh) {
              state.xzBom.mesBomBs[index].tds.splice(index2, 1)
              if (state.xzBom.mesBomBs[index].tds.length === 0) {
                state.xzBom.mesBomBs[index].td = false
              }
            }
          })
        }
      }
    })
  }

  const quedingBaocun = async () => {
    if (state.xzBom.mesBomBs.length > 0) {
      const { code } = await updateApi(state.xzBom)
      if (code === 2000) {
        $baseMessage('保存成功', 'success')
        baocunqidong.value = false
        state.xzBom = {}
        let params = {
          pkInv: state.xzInv.pkInv,
        }
        const { code, data } = await getBomApi(params)
        if (code === 2000) {
          state.bomData = data
        }
      } else {
        $baseMessage('保存失败', 'warning')
      }
    } else {
      $baseMessage('明细不能为空！', 'warning')
    }
  }

  const tableRowClassName = ({ row }) => {
    if (row.isTd) {
      return 'success-row'
    }
  }

  const jiaTidai = (index, row) => {
    state.currentRowData = row
    state.currentIndex = index
    state.currentPk = row.hh
    xztd.value.handleOpen({ isComsume: 1 }, 2)
  }

  const selectedCallback = (xuanZinv, type) => {
    console.log(xuanZinv)
    console.log(type)
    if (0 === type) {
      getBom(xuanZinv)
    } else if (1 === type) {
      zengjiaXuanze(xuanZinv)
    } else if (2 === type) {
      xuanzeTidai(xuanZinv)
    }
  }
  const getBom = async (xuanZinv) => {
    let params = {
      pkInv: xuanZinv.pkInv,
    }
    state.xzInv.invcode = xuanZinv.invcode
    state.xzInv.pkInv = xuanZinv.pkInv
    const { code, data } = await getBomApi(params)
    if (code === 2000 && data.length > 0) {
      state.bomData = data
    } else if (code === 2000 && data.length <= 0) {
      const arr = []
      arr.push(xuanZinv)
      state.bomData = arr
    }
  }
  const zengjiaXuanze = (xuanZinv) => {
    let map = {
      childFSl: 0,
      childPkInv: xuanZinv.pkInv,
      childSl: 1,
      hh: state.zenghang.hh,
      pkInv: xuanZinv.pkInv,
      invcode: xuanZinv.invcode,
      invname: xuanZinv.invname,
      invspec: xuanZinv.invspec,
      invtype: xuanZinv.invtype,
      measname: xuanZinv.measName,
      mesBomHs: [],
      opCode: '',
      opName: '',
      parentFsl: 0,
      parentSl: 1,
      pkBomB: '',
      pkBomH: state.xzBom.pkBomH,
      pkCorp: state.xzBom.pkCorp,
      pkGx: '',
      td: false,
      tds: [],
      zyx1: 'zyx',
      isLingyong: true,
    }
    state.xzBom.mesBomBs.splice(state.zenghang.index + 1, 0, map)
  }
  const xuanzeTidai = (xuanZinv) => {
    let map = {
      pkBomB: state.currentRowData.pkBomB,
      hh: parseInt('9' + state.currentRowData.hh),
      pkGx: state.currentRowData.pkGx,
      pkBomH: state.currentRowData.pkBomH,
      pkCorp: state.currentRowData.pkCorp,
      opName: state.currentRowData.opName,
      pkInv: xuanZinv.pkInv,
      invcode: xuanZinv.invcode,
      invname: xuanZinv.invname,
      invspec: xuanZinv.invspec,
      invtype: xuanZinv.invtype,
      measname: xuanZinv.measName,
      childSl: state.currentRowData.childSl,
      childFsl: state.currentRowData.childFsl,
      parentSl: state.currentRowData.parentSl,
      parentFsl: state.currentRowData.parentFsl,
      zyx1: state.currentRowData.zyx1,
      isTd: true,
      isLingyong: true,
    }
    state.xzBom.mesBomBs.forEach((element) => {
      if (element.hh === state.currentPk) {
        if (element.tds.length === 0) {
          element.tds.push(map)
          element.td = true
        } else {
          map.hh = element.tds[element.tds.length - 1].hh + 1
          element.tds.push(map)
          element.td = true
        }
      }
    })
  }

  const query = () => {
    xzi.value.handleOpen({ isSelf: 1 }, 0)
  }

  const bomTreeRowClick = async (bomData) => {
    state.xzBom = bomData
    let parmas = {
      pkCorp: pkCorp,
      pkInv:
        bomData.parentPkInv === undefined ? bomData.pkInv : bomData.parentPkInv,
    }
    if (parmas.pkInv) {
      const { code, data } = await getOperForBomApi(parmas)
      if (code === 2000) {
        state.gxs = data
      }
    }
  }

  onMounted(async () => {
    if (route.query.pkInv && route.query.invcode) {
      let params = {
        pkInv: route.query.pkInv ? route.query.pkInv : '',
      }
      const { code, data } = await getBomApi(params)
      if (code === 2000) {
        state.bomData = data
      }
    }
  })

  watch(route, async () => {
    if (route.query.pkInv && route.query.invcode) {
      let params = {
        pkInv: route.query.pkInv ? route.query.pkInv : '',
      }
      const { code, data } = await getBomApi(params)
      if (code === 2000) {
        state.bomData = data
      }
    }
  })
</script>

<style lang="scss">
  .el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
  }
</style>
